import { useEffect, useRef, useState } from "react"

export const isFalsy = (value:unknown)=> value === 0 ?false : !value
export const isVoid = (value:unknown) => value === undefined || value === null || value ===''

// 在一个函数里，改变传入的对象本身是不好的
export const cleanObject=(object:{[key:string]:unknown})=>{
  const result = {...object}
  Object.keys(result).forEach(key =>{
    const value = object[key]
    if(isFalsy(value)){
        //  @ts-ignore 意思？
      delete result[key]
    }
  })
  return result
}

export const useMount =(callback:()=>void,value?:string)=>{
  useEffect(()=>{
    callback()
  },[value])
}

// const debounce = (func,delay) =>{
//   let timeout;
//   return (...param)=>{
//     if(timeout){
//       clearTimeout(timeout)
//     }
//     timeout = setTimeout(() => {
//       func(...param)
//     }, delay);
//   }
// }

// export const useDebounce = (value:unknown, delay?:number):any =>{
//   const [debouncedValue, setDebouncedValue] = useState(value)

//   useEffect(()=>{
//     // 每次在value变化以后，设置一个定时器
//     const timeout = setTimeout(()=>{setDebouncedValue(value)},delay)
//     // 每次在上一个useEffect处理完以后再运行
//     return ()=>{clearTimeout(timeout)}
//   },[value])

//   return debouncedValue
// }

// 泛型使用
export const useDebounce =<V> (value:V, delay?:number): any=>{
  const [debouncedValue, setDebouncedValue] = useState(value)

  useEffect(()=>{
    // 每次在value变化以后，设置一个定时器
    const timeout = setTimeout(()=>{setDebouncedValue(value)},delay)
    // 每次在上一个useEffect处理完以后再运行
    return ()=>{clearTimeout(timeout)}
  },[value,delay])

  return debouncedValue
}

export const useDocumentTitle = (title: string,keepOnUnmount:boolean = true) =>{
  // const oldTitle = document.title
  const oldTitle = useRef(document.title).current
  useEffect(()=>{
    document.title = title
  },[title])

  useEffect(()=>{
    return()=>{
      if(!keepOnUnmount){
        document.title = oldTitle
      }
    }
  },[keepOnUnmount,oldTitle])
}

export const resetRouter =()=> window.location.href = window.location.origin

/**
 * 返回组件的挂载状态，如果还没挂载或者已经卸载，返回false;反之返回TRUE
 */

export const useMountedRef = () =>{
  const mountedRef = useRef(false)

  useEffect(()=>{
    mountedRef.current = true
    return () =>{
      mountedRef.current = false 
    }
  })

  return mountedRef
}